package com.ruoyi.web.controller.common;


import com.alibaba.fastjson.JSONObject;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by XPF on 2024/11/15.
 * 说明：
 */
public class AESUtil {

    private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding";
    public static SecretKeySpec generateKey(byte[] key) throws Exception {
        return new SecretKeySpec(key, "AES");
    }

    public static String encrypt(String keySec, String data) throws Exception {
        return new BASE64Encoder().encode(calculate(keySec, data.getBytes(),Cipher.ENCRYPT_MODE));
    }

    public static String decrypt(String keySec, String data) throws Exception {
        return new String(calculate(keySec, new BASE64Decoder().decodeBuffer(data),Cipher.DECRYPT_MODE));
    }

    private static byte[] calculate(String keySec, byte[] data, int mode) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
        cipher.init(mode, generateKey(keySec.getBytes()));
        return cipher.doFinal(data);
    }


    public static void main(String[] args) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("appId", "632c5d06185c4ed58fa0c75ab409a9cb");
        map.put("time", new Date().getTime());
        String encode = encrypt("c44059f37a6d493588b92b8e92667bde", JSONObject.toJSONString(map));
        System.out.println("加密后：" + encode);

        Thread.sleep(2000);
        System.out.println("睡上2秒");

        String decode = decrypt("c44059f37a6d493588b92b8e92667bde", encode);
        System.out.println("解密后：" + decode);
        JSONObject json = JSONObject.parseObject(decode);

        if((new Date().getTime() - json.getLongValue("time")) > 5000) {
            System.out.println("超时了");
        } else {
            System.out.println("没问题");
        }
    }
}
